# -*- coding:UTF-8 -*-


import requests
from bs4 import BeautifulSoup
import string
import random
import time


class Smzdm(object):
    def __init__(self, targetUrl):
        super(Smzdm, self).__init__()
        self.__targetUrl = targetUrl
        self.__header = {
            'User-Agent': 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19', }

    def getDownloadUrl(self):
        response = requests.get(self.__targetUrl, headers=self.__header, verify=False)
        print(response)
        if response.status_code == 200:
            html = response.content.decode('gbk', 'ignore').encode('utf-8')
        else:
            html = "<html></html>"
        soup = BeautifulSoup(html, 'lxml')
        obj = {}
        idx = 1
        fileName = 'detail' + str(int(round(time.time() * 1000))) + '.csv'

        items = soup.find_all(id='J_scroll_ul')
        for item in items:
            link = item.a['href']
            title = item.find(class_='zm-card-title').text
            price = item.find(class_='card-price').text.strip() if item.find(class_='card-price') else '0'
            source = item.find(class_='card-mall').text.strip() if item.find(class_='card-mall') else 'Unknown'
            detail = "%s,%s,%s,%s" % (title, price, source, link)
            with open(fileName, 'a', encoding='utf-8') as f:
                f.write(detail + '\n')
            # print(detail)
            obj[idx] = detail
            idx = idx + 1
        print(obj)


if __name__ == "__main__":
    smzdm = Smzdm("https://www.smzdm.com/")
    smzdm.getDownloadUrl()
